2619. Array Prototype Last
Easy
- 題目描述
- 解答
Description
Write code that enhances all arrays such that you can call thearray.last()method on any array and it will return the last element. If there are no elements in the array, it should return-1.
You may assume the array is the output ofJSON.parse.
Example 1:
Input: nums = [null, , 3]
Output: 3
Explanation: Calling nums.last() should return the last element: 3.
Example 2:
Input: nums = []
Output: -1
Explanation: Because there are no elements, return -1.
Constraints:
arris a valid JSON array0 <= arr.length <= 1000
Solution
/**
* @return {null|boolean|number|string|Array|Object}
*/
Array.prototype.last = function () {
if (this.length === 0) return -1;
return this[this.length - 1];
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
解題思路
題目要求是替 Array 新增一個 .last() 方法,來取得陣列的最後一個元素。
由於是在 Array.prototype 上新增,故在解題時可以使用 this 來取得當前陣列本身。
直接使用 this[this.length - 1] 來取得最後一個元素即可。
而當陣列長度為 0 時,依照題目要求直接回傳 -1。
心得
直接操作 prototype 還滿少見的,剛好可以練習這種做法。